package csl.blog.client.netty.base;

import csl.blog.client.netty.handler.ClientHeartbeatHandler;
import csl.blog.client.netty.handler.ResponseChannelHandler;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.timeout.IdleStateHandler;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @author chensl
 * @date 2023-04-19 16:22:17
 * @description
 */
@Slf4j
@Component
public class NettyClientChannelInitializer extends ChannelInitializer {

    private final ResponseChannelHandler responseChannelHandler;

    private final ClientHeartbeatHandler clientHeartbeatHandler;

    public NettyClientChannelInitializer(ResponseChannelHandler responseChannelHandler, ClientHeartbeatHandler clientHeartbeatHandler) {
        this.responseChannelHandler = responseChannelHandler;
        this.clientHeartbeatHandler = clientHeartbeatHandler;
    }

    @Override
    protected void initChannel(Channel channel) {
        channel.pipeline().addLast(new IdleStateHandler(0, 30, 0, TimeUnit.SECONDS));
        channel.pipeline().addLast("decoder",new StringDecoder(CharsetUtil.UTF_8));
        channel.pipeline().addLast("encoder",new StringEncoder(CharsetUtil.UTF_8));
        channel.pipeline().addLast("responseChannelHandler",responseChannelHandler);
        channel.pipeline().addLast("clientHeartbeatHandler", clientHeartbeatHandler);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.error("error message {}",cause.getMessage(),cause);
        super.exceptionCaught(ctx, cause);
    }
}
